package com.lebang.configuration.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.common.Require;
import com.lebang.entity.RequestHeaders;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.service.buss.MemberService;
import com.lebang.service.sys.DictService;
import com.lebang.service.sys.PkgBlackLogService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URLEncoder;

/**
 * 自定义拦截器
 * 对用户登陆状态校验
 *
 * @author Eli
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {
    @Autowired
    private MemberService memberService;
    @Autowired
    private PkgBlackLogService pkgBlackLogService;
    @Autowired
    private DictService dictService;
    private static final Logger log = LoggerFactory.getLogger(BaseInterceptor.class);

    /**
     * 该方法将在请求处理之前进行调用，只有该方法返回true，才会继续执行后续的Interceptor和Controller，
     * 当返回值为true 时就会继续调用下一个Interceptor的preHandle 方法，
     * 如果已经是最后一个Interceptor的时候就会是调用当前请求的Controller方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
               //String uri = request.getRequestURI();
        //log.info(uri);
        RequestHeaders requestHeaders = new RequestHeaders(request);
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(Require.class)) {
            Require userLoginToken = method.getAnnotation(Require.class);
            if (userLoginToken.required()) {
                String userid = requestHeaders.getUserid();
                userid = userid == null ? "" : userid;
                if ("".equals(userid)) {
                    responseMsg(response, "600", "请先登录！");
                    return false;
                }
                String appid = requestHeaders.getAppid();
                // 校验应用
                if (null == appid || "".equals(appid)) {
                    responseMsg(response, "600", "请先打开应用！");
                    return false;
                }
//                Integer fail = pkgBlackLogService.pkgBlackLogService(requestHeaders);
//                if (fail != null) {
//                    String qq = dictService.selectByKeyName("manager_qq").getKeyvalue();
//                    responseMsg(response, "600", "账户异常禁止登陆,请联系管理员Q号:"+qq+"!");
//                    return false;
//                }
                String status = memberService.checkMemberByMemberId(userid);

                if (status == null) {
                    responseMsg(response, "600", "请先登录！");
                    return false;
                }
                if (status.equals(UserStatus.Close.name())) {
                    responseMsg(response, "600", "账户异常禁止登陆,请联系管理员!");
                    return false;
                }

                if (status.equals(UserStatus.CheckSuccess.name())) {
                    responseMsg(response, "600", "账户已注销!");
                    return false;
                }

            }
        }

        if (method.isAnnotationPresent(Login.class)) {
            HttpSession session = request.getSession();
            String userid = (String) session.getAttribute("userid");
            Login userLoginToken = method.getAnnotation(Login.class);
            if (userLoginToken.required()) {

                if (null == userid || "".equals(userid)) {
                    String str = URLEncoder.encode("登陆信息已过期请重新登录！", "utf-8");
                    response.sendRedirect("/login?err=" + str);
                    responseMsg(response, "invalid", "登陆信息已过期请重新登录！");
                    return false;
                } else {
                    session.setAttribute("userid", userid);
                    session.setMaxInactiveInterval(10000);
                }
            }
        }
        return true;
    }

    private void responseMsg(HttpServletResponse response, String status, String msg) throws IOException {
        JsonData jsonData = Callback.fail(status, msg, "");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; CHARSET=utf-8");
        String json = JSONObject.toJSONString(jsonData);
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }


    /**
     * 该方法将在请求处理之后，DispatcherServlet进行视图返回渲染之前进行调用，可以在这个方法中对Controller 处理之后的ModelAndView 对象进行操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行，该方法将在整个请求结束之后，也就是在DispatcherServlet 渲染了对应的视图之后执行。用于进行资源清理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
